In C, a string is a sequence of characters stored in an array with a null terminator ('\0') at the end. Since C does not have a built-in string data type, strings are represented as character arrays. Each character in the string is stored in consecutive memory locations, and the null terminator marks the end of the string. To work with strings, C provides various standard library functions defined in string.h.
To declare and initialize a string in C, you can use a character array with enough size to hold the characters and the null terminator.
char string_name[] = "Hello, World!";
#include <stdio.h>
#include <string.h>
int main() {
// Declaration and initialization of a string
char message[] = "Hello, World!";
// Printing the entire string
printf("Message: %s\n", message);
// Finding the length of the string
int length = strlen(message);
printf("Length of the string: %d\n", length);
// Accessing individual characters in the string
printf("Characters: ");
for (int i = 0; i < length; i++) {
printf("%c ", message[i]);
}
printf("\n");
// Modifying the string
message[7] = 'M'; // Change 'W' to 'M'
// Printing the modified string
printf("Modified Message: %s\n", message);
// Concatenating two strings
char name[] = "John";
char greeting[20];
strcpy(greeting, "Hello, ");
strcat(greeting, name);
// Printing the concatenated string
printf("Greeting: %s\n", greeting);
return 0;
}
Message: Hello, World!
Length of the string: 13
Characters: H e l l o , W o r l d !
Modified Message: Hello, Morld!
Greeting: Hello, John
What is a string in C?
What character is used to terminate a string in C?
What library should you include for string functions in C?
How do you compare two strings in C?
What C function is used to find the length of a string?